package com.android.settings.audio.peq.soundeffect;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.android.settings.R;
import com.android.settings.audio.peq.user.Callback;
import com.android.settings.audio.peq.user.HibyUser;
import com.android.settings.audio.peq.user.UserManager;
import com.android.settings.audio.peq.util.BuildConfig;
import com.android.settings.audio.peq.util.LogPlus;
import com.android.settings.audio.peq.util.NetWorkUtils;
import com.android.settings.audio.peq.util.ShareprefenceTool;
import com.android.settings.audio.peq.util.SmartPlayerApplication;
import com.android.settings.audio.peq.util.ToastTool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by We on 2023/6/13
 */
public class ServerConfigManager {
    public static final class InstanceHolder {
        private static final ServerConfigManager instance = new ServerConfigManager();
    }

    public static ServerConfigManager getInstance() {
        return InstanceHolder.instance;
    }

    public void savePluginConfigToServer(String type, Object list, Callback<String> callback) {
        if (UserManager.getInstance().currentActiveUser() == null) {
            ToastTool.showToast(SmartPlayerApplication.getInstance(), SmartPlayerApplication.getInstance().getString(R.string.peq_plg_net_notlogin_details));//未登录则不提交
            return;
        }
        boolean isNetworkAvailable = NetWorkUtils.isConnected(SmartPlayerApplication.getInstance());
        if (!isNetworkAvailable) {//网络不可用则暂不提交
            return;
        }
        /*UserManager.getInstance().savePluginConfig(UserManager.getInstance().currentActiveUser().email(), type, UserManager.getInstance().currentActiveUser().token(), list).call(new Callback<String>() {
            @Override
            public void onSuccess(String data) {
                if (BuildConfig.DEBUG) LogPlus.d("onSuccess: " + data);
                if (callback != null) callback.onSuccess(data);
            }

            @Override
            public void onError(Throwable t) {
                t.printStackTrace();
                if (callback != null) callback.onError(t);
            }
        });*/
    }

    public List<PluginConfigItem> getConfigs(String type, String title, String device, String sn, String desc, SoundEffectConfig soundEffectConfig) {
        List<PluginConfigItem> jsonArray = new ArrayList<>();
        PluginConfigItem pluginConfigItem = new PluginConfigItem();
        pluginConfigItem.id = null;
        pluginConfigItem.title = title;
        pluginConfigItem.device = device;
        pluginConfigItem.serialNo = sn;
        pluginConfigItem.description = desc;
        pluginConfigItem.configInfo = null;

        if (soundEffectConfig.isServerConfig()) {
            //属于服务器端的配置, 传入更新id
            pluginConfigItem.id = soundEffectConfig.getServerConfigData().getId();
            pluginConfigItem.configInfo = soundEffectConfig.getConfigData();
        } else {
            // 本地配置, todo 需要检查是否对应有服务器端的配置, 否则也应该传入更新id
            if (!TextUtils.isEmpty(soundEffectConfig.getServerDataId())) {
                pluginConfigItem.id = Long.valueOf(soundEffectConfig.getServerDataId());
            }
            if ("peq".equals(type)) {
                PluginDataManager.PeqData peqData = PluginDataManager.getInstance().getPluginDataValue(PluginDataManager.KEY_PEQ, soundEffectConfig.getId(), new TypeToken<PluginDataManager.PeqData>() {
                });
                if (null != peqData) {
                    ServerPeqDataConfig serverPeqDataConfig = new ServerPeqDataConfig();
                    serverPeqDataConfig.bands = peqData.bands;
                    serverPeqDataConfig.pre_amp = peqData.pre_amp;
                    pluginConfigItem.configInfo = serverPeqDataConfig;
                }
            } else if ("eq".equals(type)) {
                PluginDataManager.PluginData pluginData = PluginDataManager.getInstance().getPluginData(PluginDataManager.KEY_EQ, soundEffectConfig.getId());
                if (pluginData != null) {
                    ServerEqDataConfig serverEqDataConfig = new ServerEqDataConfig();
                    PluginDataManager.EqData eqData = null;
                    if (!(pluginData.getValue() instanceof PluginDataManager.EqData)) {
                        try {
                            eqData = PluginDataManager.getInstance().jsonToData(PluginDataManager.getInstance().toJson(pluginData.getValue()), PluginDataManager.EqData.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        eqData = (PluginDataManager.EqData) pluginData.getValue();
                    }
                    if (eqData != null) {
                        serverEqDataConfig.setValue(eqData.value);
                        pluginConfigItem.configInfo = serverEqDataConfig;
                    }
                }
            } else if ("mseb".equals(type)) {
                PluginDataManager.PluginData pluginData = PluginDataManager.getInstance().getPluginData(PluginDataManager.KEY_MSEB, soundEffectConfig.getId());
                if (pluginData != null) {
                    ServerMsebDataConfig serverMsebDataConfig = new ServerMsebDataConfig();
                    PluginDataManager.MsebData msebData = null;
                    if (!(pluginData.getValue() instanceof PluginDataManager.EqData)) {
                        try {
                            msebData = PluginDataManager.getInstance().jsonToData(PluginDataManager.getInstance().toJson(pluginData.getValue()), PluginDataManager.MsebData.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        msebData = (PluginDataManager.MsebData) pluginData.getValue();
                    }
                    if (msebData != null) {
                        serverMsebDataConfig.setDatalist(msebData.datalist);
                        serverMsebDataConfig.setRange(msebData.range);
                        pluginConfigItem.configInfo = serverMsebDataConfig;
                    }
                }
            }
        }
        if (BuildConfig.DEBUG) LogPlus.d("###pluginConfigItem:" + pluginConfigItem);
        jsonArray.add(pluginConfigItem);
        return jsonArray;
    }

    public static class PluginConfigItem {
        private Long id;
        private String title = "test";
        private String device = "test";
        private String serialNo = "test";
        private String description = "test";
        private Object configInfo = new Object();

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDevice() {
            return device;
        }

        public void setDevice(String device) {
            this.device = device;
        }

        public String getSerialNo() {
            return serialNo;
        }

        public void setSerialNo(String serialNo) {
            this.serialNo = serialNo;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public Object getConfigInfo() {
            return configInfo;
        }

        public void setConfigInfo(Object configInfo) {
            this.configInfo = configInfo;
        }

        @Override
        public String toString() {
            return "PluginConfigItem{" +
                    "id=" + id +
                    ", title='" + title + '\'' +
                    ", device='" + device + '\'' +
                    ", serialNo='" + serialNo + '\'' +
                    ", description='" + description + '\'' +
                    ", configInfo=" + configInfo +
                    '}';
        }
    }

    public static final class ServerPeqDataConfig {
        private List<PluginDataManager.BandItem> bands;
        private double pre_amp;

        public List<PluginDataManager.BandItem> getBands() {
            return bands;
        }

        public void setBands(List<PluginDataManager.BandItem> bands) {
            this.bands = bands;
        }

        public void setPre_amp(double pre_amp) {
            this.pre_amp = pre_amp;
        }

        public double getPre_amp() {
            return pre_amp;
        }
    }

    public static final class ServerEqDataConfig {
        private float[] value;

        public void setValue(float[] value) {
            this.value = value;
        }

        public float[] getValue() {
            return value;
        }
    }

    public static final class ServerMsebDataConfig {
        private List<Integer> datalist;
        private int range;

        public List<Integer> getDatalist() {
            return datalist;
        }

        public void setDatalist(List<Integer> datalist) {
            this.datalist = datalist;
        }

        public int getRange() {
            return range;
        }

        public void setRange(int range) {
            this.range = range;
        }
    }

    public ServerConfigList getCachedConfigs(HibyUser hibyUser, String type) {
        if (userConfigs.containsKey(hibyUser)) {
            return userConfigs.get(hibyUser);
        }

        String s = ShareprefenceTool.getInstance().getStringShareprefence("cacheConfigs_user_" + getConfigCacheKey(hibyUser, type), SmartPlayerApplication.getInstance(), "");
        if (TextUtils.isEmpty(s)) {
            return null;
        }

        try {
            return new Gson().fromJson(s, ServerConfigList.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Map<String, ServerConfigList> userConfigs = new HashMap<>();

    public void cacheConfigs(HibyUser hibyUser, String type, ServerConfigList serverConfigList) {
        if (hibyUser == null || serverConfigList == null) return;
        userConfigs.put(getConfigCacheKey(hibyUser, type), serverConfigList);
        String json = new Gson().toJson(serverConfigList);
        ShareprefenceTool.getInstance().setStringSharedPreference("cacheConfigs_user_" + getConfigCacheKey(hibyUser, type), json, SmartPlayerApplication.getInstance());
    }

    public void clearCachedConfigs(HibyUser hibyUser, String type) {
        if (hibyUser == null) return;
        userConfigs.remove(getConfigCacheKey(hibyUser, type));
        ShareprefenceTool.getInstance().setStringSharedPreference("cacheConfigs_user_" + getConfigCacheKey(hibyUser, type), "", SmartPlayerApplication.getInstance());
    }

    private String getConfigCacheKey(HibyUser hibyUser, String type) {
        return /*hibyUser.name() + hibyUser.email() + "_" + type*/"";
    }
}
